package gdut.edu.demo04;

import java.util.Arrays;

/**
 * @Description 快排序
 * @Author JiaFu
 * @Date 2022/9/18 15:23
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] arr = new int[]{4, 1, 3, 5, 3, 2, 7, 2, 8};
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));

    }

    public static void quickSort(int[] arr, int start, int end) {
        if (start < end) {
            //找出基准数字
            int stand = arr[start];
            int low = start;//低位
            int high = end;//高位
            while (low < high) {
                //从high高位开始比较
                while (low < high && stand <= arr[high]) {
                    high--;
                }
                //high指向的数字小于基准数字stand,将该数字移动到low低位
                arr[low] = arr[high];
                //从low低位开始比较
                while (low < high && arr[low] <= stand) {
                    low++;
                }
                //low指向的数字大于基准数字stand,将该数字移动到high位
                arr[high] = arr[low];
            }
            //把基准数字填回来
            arr[low] = stand;
            //小的数字排序
            quickSort(arr, start, low);
            //大的数字排序
            quickSort(arr, low + 1, end);
        }
    }
}
